package com.ebt.m.proposal_v2.widget.dialog;

import android.app.Dialog;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ebt.m.R;
import com.ebt.m.commons.utils.ActivityUtils;
import com.ebt.m.proposal_v2.voice.TapApi;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 语音录制提示窗口
 *
 * @author archer.qi
 *         Created on 2017/5/19.
 */
public class TapTipDialog extends DialogFragment {
    private View mContentView;

    @BindView(R.id.tip_content)
    TextView mTextContent;
    @BindView(R.id.tip_mode_1)
    ImageView mMode1;
    @BindView(R.id.tip_mode_2)
    LinearLayout mMode2;
    @BindView(R.id.tip_mode_3)
    TextView mMode3;
    @BindView(R.id.tip_mode_2_volume)
    ImageView mMode2Volume;

    private int mode;
    private int countdown;
    private String tipMsg;
    private CountDownTimer mTimer;

    private long SAMPLING_INTERVAL = 50; /* 录音取样间隔*/
    private int RECORDING_VOLUME_BASE = 600; /* 噪音的振幅，保证在不说话的情况下，声音的振幅为0*/
    private int MAX_DECIBEL_LEVEL = 5; /* 设定说话最大分贝为50，这里是/10之后的值*/
    private Handler mSamplingHandler = new Handler() { /* 录音振幅强度刷新*/
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (mode == 2) { /* 正在录音时生效*/
                int currentDecibel = getRecordVolume();
                int volRatio = currentDecibel / MAX_DECIBEL_LEVEL;
                if (volRatio == 0) {
                    mMode2Volume.setImageDrawable(null);
                } else {
                    mMode2Volume.setImageResource(getVolumeImage(volRatio));
                }
                mSamplingHandler.sendEmptyMessageDelayed(0, SAMPLING_INTERVAL);
            }
        }
    };

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (mContentView == null) {
            getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
            mContentView = inflater.inflate(R.layout.dialog_tap_tip, container, false);
            ButterKnife.bind(this, mContentView);
            init();
        }
        if (mContentView != null) {
            ViewGroup parent = (ViewGroup) mContentView.getParent();
            if (parent != null) {
                parent.removeAllViews();
            }
        }
        return mContentView;
    }

    private void init() {
        initTip();
    }

    private void setMode(int mode) {
        switch (mode) {
            case 1: // !提示
                mMode1.setVisibility(View.VISIBLE);
                mMode2.setVisibility(View.GONE);
                mMode3.setVisibility(View.GONE);
                break;
            case 2: // 语音及音量控制
                mMode2.setVisibility(View.VISIBLE);
                mMode1.setVisibility(View.GONE);
                mMode3.setVisibility(View.GONE);
                break;
            case 3: // 倒计时
                mMode3.setVisibility(View.VISIBLE);
                mMode1.setVisibility(View.GONE);
                mMode2.setVisibility(View.GONE);
                break;
            default:
                mMode1.setVisibility(View.GONE);
                mMode2.setVisibility(View.GONE);
                mMode3.setVisibility(View.GONE);
                break;
        }
        this.mode = mode;
    }

    private int getVolumeImage(int vol) {
        switch (vol) {
            case 1:
                return R.drawable.ic_volume1;
            case 2:
                return R.drawable.ic_volume2;
            case 3:
                return R.drawable.ic_volume3;
            case 4:
                return R.drawable.ic_volume4;
            case 5:
                return R.drawable.ic_volume5;
            case 6:
                return R.drawable.ic_volume6;
            case 7:
                return R.drawable.ic_volume7;
            case 8:
                return R.drawable.ic_volume8;
            case 9:
                return R.drawable.ic_volume9;
            default:
                return R.drawable.ic_volume9;
        }
    }

    private void initTip() {
        if (mode == 3) { // 倒计时
            mTextContent.setText("松开 录制结束");
            setMode(3);
            mMode3.setText(countdown + "");
        }
        if (mode == 2) { // 正在录音
            mTextContent.setText("松开 录制结束");
            setMode(2);
//            mSamplingHandler.sendEmptyMessageDelayed(0, SAMPLING_INTERVAL);
        }
        if (mode == 1) { // 提示： 录音时间过短
            mTextContent.setText(tipMsg);
            setMode(1);
        }
    }

    /**
     * 获取录音麦克风分贝
     *
     * @return
     */
    private int getRecordVolume() {
        MediaRecorder recorder = TapApi.getApi().getMediaRecoder();
        if (recorder == null) {
            return 0;
        }
        int currAmplitude = recorder.getMaxAmplitude();
        int ratio = currAmplitude / RECORDING_VOLUME_BASE;
        double decibel = 0;
        if (ratio > 1) {
            decibel = 20 * Math.log10(ratio);
        }
        return (int) decibel;
    }

    public TapTipDialog showCountDown(int countdown) {
        boolean isShowing = getDialog() == null ? false : getDialog().isShowing();
        this.mode = 3;
        this.countdown = countdown;
        if (isShowing && mMode3 != null) {
            mMode3.setText(countdown + "");
        }
        return this;
    }

    public TapTipDialog showTip(String tip) {
        this.mode = 1;
        this.tipMsg = tip;
        return this;
    }

    public TapTipDialog showRecordingVolume() {
        this.mode = 2;
        return this;
    }

    public TapTipDialog setRecordingVolume(int volume) {
        if (mMode2Volume == null) {
            return this;
        }
        if (volume == 0) {
            mMode2Volume.setImageDrawable(null);
        } else {
            mMode2Volume.setImageResource(getVolumeImage(volume));
        }
        return this;
    }

    @Override
    public void show(FragmentManager manager, String tag) {
        if (mode == 1) {
            startDurationTimer();
        }
        super.show(manager, tag);
    }

    @Override
    public int show(FragmentTransaction transaction, String tag) {
        if (mode == 1) {
            startDurationTimer();
        }
        return super.show(transaction, tag);
    }

    private void startDurationTimer() {
        mTimer = new CountDownTimer(2000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {

            }

            @Override
            public void onFinish() {
                dismiss();
            }
        };
        mTimer.start();
    }

    @Override
    public void dismiss() {
        if (mSamplingHandler != null) {
            mSamplingHandler.removeMessages(0);
            mSamplingHandler = null;
        }
        super.dismiss();
    }

    @Override
    public void onResume() {
        super.onResume();
        resizeDialog();
    }

    @Override
    public void onStart() {
        super.onStart();
        removeBorder();
    }

    /**
     * 设定DIALOG大小与位置
     */
    private void resizeDialog() {
        float density = ActivityUtils.getScreenDensity(getActivity());
        int size = (int) (142 * density);

        Dialog mDialog = getDialog();
        WindowManager.LayoutParams p = mDialog.getWindow().getAttributes();
        p.width = size;
        p.height = size;
        p.gravity = Gravity.CENTER;
        mDialog.getWindow().setAttributes(p);

        mDialog.getWindow().setBackgroundDrawable(null);
        mDialog.setCancelable(false);
        mDialog.setCanceledOnTouchOutside(false);
    }

    /**
     * 去边框
     */
    private void removeBorder() {
        Dialog dialog = getDialog();
        if (dialog != null) {
            dialog.getWindow().setLayout(-1, -2);
        }
    }

}
